package com.wish233.wiliwilivideo.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.wish233.wiliwilicommon.common.BaseResponse;
import com.wish233.wiliwilicommon.common.ErrorCode;
import com.wish233.wiliwilicommon.common.ResultUtils;
import com.wish233.wiliwilicommon.exception.BusinessException;
import com.wish233.wiliwilicommon.exception.ThrowUtils;
import com.wish233.wiliwilivideo.domain.dto.upload.UploadFileRequest;
import com.wish233.wiliwilivideo.domain.enums.FileUploadBizEnum;
import com.wish233.wiliwilivideo.utils.UploadUtil;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.MultimediaObject;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * 文件上传控制器
 *
 * @author WHH
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    public static final String COS_URL = "https://wiliwili-1254289387.cos.ap-guangzhou.myqcloud.com";
    @Resource
    private UploadUtil uploadUtil;

    /**
     * 上传简单文件（小于20M）
     *
     * @param multipartFile 上传的文件
     * @return 上传url
     */
    @ApiOperation("简单上传图片")
    @PostMapping("/upload/simple")
    public BaseResponse<String> uploadSimpleFile(@RequestParam("file") MultipartFile multipartFile, UploadFileRequest uploadFileRequest) {
        String filePath = getFilePath(uploadFileRequest, multipartFile);
        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(filePath, null);
            multipartFile.transferTo(file);
            // 调用工具类上传文件
            uploadUtil.simplePut(filePath, file);
            return ResultUtils.success(COS_URL + filePath);
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, e.getMessage());
        } finally {
            if (file != null) {
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete) {
                    log.error("简单上传失败, filepath = {}", filePath);
                }
            }
        }
    }

    /**
     * 上传大文件（支持分块上传）
     *
     * @param multipartFile 上传的文件
     * @return 上传结果
     */
    @SneakyThrows
    @ApiOperation("分块上传视频")
    @PostMapping("/upload/large")
    public BaseResponse<String> uploadLargeFile(@RequestParam("file") MultipartFile multipartFile, UploadFileRequest uploadFileRequest) {
        String filePath = getFilePath(uploadFileRequest, multipartFile);
        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(filePath, null);
            multipartFile.transferTo(file);
            // 调用工具类上传文件
            uploadUtil.upload(filePath, file);
            MultimediaObject multimediaObject = new MultimediaObject(file);
            long duration = multimediaObject.getInfo().getDuration();
            String result = COS_URL + filePath +
                    "|" +
                    duration;
            return ResultUtils.success(result);
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, e.getMessage());
        } finally {
            if (file != null) {
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete) {
                    log.error("分块上传失败 = {}", filePath);
                }
            }
        }
    }

    /**
     * 获取上传进度
     *
     * @param key 上传任务key
     * @return 上传进度
     */
    @ApiOperation("获取上传进度")
    @GetMapping("/upload/progress")
    public BaseResponse<Double> getUploadProgress(String key) {
        // 这里需要根据 uploadId 获取对应的 Transfer 对象
        // 假设您有一个方法来根据 uploadId 获取 Transfer 对象
        ThrowUtils.throwIf(ObjectUtil.isEmpty(key), ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(uploadUtil.showTransferProgress(key));
    }

    private String getFilePath(UploadFileRequest uploadFileRequest, MultipartFile multipartFile) {
        String biz = uploadFileRequest.getBiz();
        //获取业务
        FileUploadBizEnum enumByValue = FileUploadBizEnum.getEnumByValue(biz);
        ThrowUtils.throwIf(enumByValue == null, new BusinessException(ErrorCode.PARAMS_ERROR));
        String uuid = RandomUtil.randomString(8);
        String filename = uuid + "-" + multipartFile.getOriginalFilename();
        Object loginId = StpUtil.getLoginId();
        return String.format("/%s/%s/%s", enumByValue.getValue(), loginId, filename);
    }
}